/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DepUpPanel.java
 *
 * Created on 01/12/2011, 01:37:09
 */
package proj5labbd.graphics.dependente;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel referente à atualização de dados dos dependentes
 */
public class DepUpPanel extends OperationPanel {

    /** Creates new form DepUpPanel */
    public DepUpPanel(DepFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbUpdate.addActionListener(new DepAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbNome = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbDataNasc1 = new javax.swing.JLabel();
        jlbSexo1 = new javax.swing.JLabel();
        jcbSexo = new javax.swing.JComboBox();
        jlbFuncionario1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtFuncionario = new javax.swing.JTable();
        jftxtDate = new javax.swing.JFormattedTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbUpdate = new javax.swing.JTable();
        jbUpdate = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de atualização"));

        jlbNome.setText("Nome Completo");

        jlbDataNasc1.setText("Data de Nascimento");

        jlbSexo1.setText("Sexo");

        jcbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "F", "M" }));

        jlbFuncionario1.setText("Funcionário");

        jtFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtFuncionario);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbFuncionario1)
                        .addContainerGap(446, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(25, 25, 25)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbDataNasc1, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbSexo1)
                            .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbSexo1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jlbNome)
                            .addComponent(jlbDataNasc1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbFuncionario1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtbUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbUpdate);

        jbUpdate.setText("Atualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jbUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(jbUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    //ação tomada após a apresentação do painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações das tabelas.");
        }
    }//GEN-LAST:event_formComponentShown

    //ação tomada após o click do mouse sobre o painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtFuncionario.clearSelection();
        jtbUpdate.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbUpdate;
    private javax.swing.JComboBox jcbSexo;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbDataNasc1;
    private javax.swing.JLabel jlbFuncionario1;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbSexo1;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtFuncionario;
    private javax.swing.JTable jtbUpdate;
    private javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables

    //configuração da(s) tabela(s) a partir da aquisição de dados da base de dados
 private void setupTable() throws SQLException {
        
        String [] titles = {"ID do funcionário","Nome","Data de nascimento","Sexo",
            "Paternidade"};
        String [] fields = {"dependente.idFu","dependente.nomeCompletoDe","dependente.dataNascimentoDe","dependente.sexoDe",
            "funcionario.nomeCompletoFu"};
        String [] params = {"funcionario.idFu=dependente.idFu"};
        String [][] s = dbInterface.view(fields, params, new String[]{"dependente","funcionario"});
        
        DefaultTableModel model = new DefaultTableModel(s,titles);
        jtbUpdate.setModel(model);
    }
    
    //ouvinte do botção de atualização
    class DepAction implements ActionListener {
        //ação tomada após o botão ser pressionado
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtxtNome.getText().trim().compareTo("") != 0) {
                fields.add("dependente.nomeCompletoDe='"+jtxtNome.getText()+"'");
            }
            
            if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                fields.add("dependente.dataNascimentoDe=TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
            }
            
            if (jcbSexo.getSelectedItem().toString().compareTo("") != 0) {
                fields.add("dependente.sexoDe='" + jcbSexo.getSelectedItem().toString()+"'");
            }
            
            if (fields.size() > 0 && jtbUpdate.getSelectedRowCount() > 0) {
                String [] s = new String[2];
                String [] params = new String[2];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtbUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        s[0] = "dependente.idFu="+jtbUpdate.getValueAt(rows[i],0).toString();
                        s[1] = "dependente.nomeCompletoDe='"+jtbUpdate.getValueAt(rows[i],1).toString()+"'";
                        params[0] = s[0];
                        params[1] = s[1];
                        dbInterface.update(fieldsArray, params,
                                new String[]{"dependente"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtbUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }

}
